<!--
 * @version: 
 * @Company:  
 * @Description: 
 * @FilePath: \src\views\tool\tpl\modal\edit\index.vue
-->
<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { getFormConfig } from './config';
  import * as _API from '../../api';
  export default defineComponent({
    name: 'tplForm',
    components: { BasicModal, BasicForm },
    emits: ['success'],
    setup(_, { emit }) {
      const isUpdate = ref(false);
      const form: any = ref({});
      const [registerForm, { resetFields, setFieldsValue, validate, setProps }] = useForm({
        labelWidth: 100,
        schemas: getFormConfig(),
        showActionButtonGroup: false,
      });

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        form.value = { ...data.record };
        await resetFields();
        setModalProps({
          confirmLoading: false,
        });
        isUpdate.value = !!data?.isUpdate;
        await setProps({
          schemas: getFormConfig(),
        });
        if (unref(isUpdate)) {
          await setFieldsValue({
            ...data.record,
            newName: data.record.name,
          });
        }
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增模板' : '模板重命名'));

      const handleSubmit = async () => {
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });
          if (!isUpdate.value) {
            await _API.addAPI({ name: values.newName });
          } else {
            await _API.editAPI({ ...values, path: form.value.path });
          }
          closeModal();
          emit('success');
        } catch {}
      };

      return { registerModal, registerForm, getTitle, handleSubmit };
    },
  });
</script>
